package com.example.springboot.utils;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private  JwtUtil jwtUtil;
//    private  String[] permitAllPath= {"/OAuth2","/login"};
    private  String[] permitAllPath;
    public JwtAuthenticationTokenFilter(String... permitAllPaths) {
        this.permitAllPath = permitAllPaths;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        if (isPermitAllPath(request,permitAllPath)) {
//            // 如果是被放行的路径，则直接放行
//            filterChain.doFilter(request, response);
//            return;
//        }
        if (!isPermitAllPath(request,permitAllPath)) {
            // 如果不是被拦截的路径，则直接放行
            filterChain.doFilter(request, response);
            System.out.println(request.getRequestURI()+"jwt放行");
            return;
        }
        System.out.println(request.getRequestURI()+"jwt拦截");
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }else {
            response.setStatus(401);
            response.setContentType("application/json");
            response.getWriter().write("{\"message\":\"Token is invalid or expired\"}");
            System.out.println("token为空");
            return;
        }
        String userName = isValidToken(token);
        if (userName != null) {
            // TODO: 验证通过，继续进行其他操作
            //通过usesname获取用户信息
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, null, null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            filterChain.doFilter(request, response);
            System.out.println("通过jwt");
        }else {
            response.setStatus(401);
            response.setContentType("application/json");
            response.getWriter().write("{\"message\":\"Token is invalid or expired\"}");
            System.out.println("token无效");
        }


    }
    private String isValidToken(String token) {
        try{
            DecodedJWT decodedJWT = jwtUtil.decodeRsa(token);
            // Token验证通过，继续进行其他操作
            Claim userName = decodedJWT.getClaim("username");//因为上面生成token只给了username
            return userName.asString();
        }catch (TokenExpiredException e) {
            // Token过期处理逻辑
            return null;
        } catch (JWTVerificationException e) {
            // Token验证失败处理逻辑
            return null;
        }
    }
    private boolean isPermitAllPath(HttpServletRequest request, String... permitAllPaths) {
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        // 在这里添加你的被放行的路径判断逻辑，比如：
        // 遍历 permitAllPaths 数组
        for (String path : permitAllPaths) {
            // 检查当前路径是否是被允许的
            if (requestURI.contains(path)) {
                return true;
            }
        }

        return false;
    }
}